from flask import render_template, redirect, url_for, flash, request, abort
from flask_login import current_user, login_required
from app import db
from app.articles import bp
from app.articles.forms import ArticleForm
from app.models import Article, Skill

@bp.route('/')
@login_required
def index():
    articles = Article.query.order_by(Article.created_at.desc()).all()
    return render_template('articles/index.html', title='知识文章列表', articles=articles)

@bp.route('/create', methods=['GET', 'POST'])
@login_required
def create():
    form = ArticleForm()
    # 获取所有技能标签供选择
    form.skills.choices = [(s.id, s.name) for s in Skill.query.all()]
    
    if form.validate_on_submit():
        article = Article(title=form.title.data, content=form.content.data, author=current_user)
        # 添加关联的技能标签
        selected_skills = Skill.query.filter(Skill.id.in_(form.skills.data)).all()
        article.skills = selected_skills
        
        db.session.add(article)
        db.session.commit()
        flash('文章已创建！')
        return redirect(url_for('articles.index'))
    return render_template('articles/create.html', title='创建文章', form=form)

@bp.route('/<int:id>')
@login_required
def view(id):
    article = Article.query.get_or_404(id)
    return render_template('articles/view.html', title=article.title, article=article)

@bp.route('/<int:id>/edit', methods=['GET', 'POST'])
@login_required
def edit(id):
    article = Article.query.get_or_404(id)
    # 检查权限：只有作者或管理员可以编辑
    if article.author != current_user and not current_user.is_admin():
        abort(403)
    
    form = ArticleForm(obj=article)
    # 获取所有技能标签供选择
    form.skills.choices = [(s.id, s.name) for s in Skill.query.all()]
    # 预选已关联的技能
    if request.method == 'GET':
        form.skills.data = [s.id for s in article.skills]
    
    if form.validate_on_submit():
        article.title = form.title.data
        article.content = form.content.data
        # 更新关联的技能标签
        selected_skills = Skill.query.filter(Skill.id.in_(form.skills.data)).all()
        article.skills = selected_skills
        
        db.session.commit()
        flash('文章已更新！')
        return redirect(url_for('articles.view', id=article.id))
    return render_template('articles/edit.html', title='编辑文章', form=form, article=article)

@bp.route('/<int:id>/delete')
@login_required
def delete(id):
    article = Article.query.get_or_404(id)
    # 检查权限：只有作者或管理员可以删除
    if article.author != current_user and not current_user.is_admin():
        abort(403)
    
    db.session.delete(article)
    db.session.commit()
    flash('文章已删除！')
    return redirect(url_for('articles.index'))

@bp.route('/by-skill/<int:skill_id>')
@login_required
def by_skill(skill_id):
    skill = Skill.query.get_or_404(skill_id)
    articles = skill.articles
    return render_template('articles/by_skill.html', title=f'{skill.name}相关文章', 
                           skill=skill, articles=articles)